package com.aw.baselib.net.callback;

import android.net.ParseException;

import com.aw.baselib.R;
import com.aw.baselib.base.AwBaseApplication;
import com.aw.baselib.bean.rx.EventReLoginType;
import com.aw.baselib.net.error.ApiException;
import com.google.gson.JsonParseException;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.functions.Consumer;
import retrofit2.HttpException;

/**
 * @author : hzw
 * @date : 2021/12/10
 */
public class AwErrorSubscriber implements Consumer<Throwable> {

    public static final int UNKNOWN_CODE = -1;
    private AwErrorCallback mThrowCallback;

    public AwErrorSubscriber(AwErrorCallback throwCallback) {
        mThrowCallback = throwCallback;
    }

    @Override
    public void accept(Throwable e) {
        if (null == mThrowCallback) {
            return;
        }
        if (e instanceof HttpException || e instanceof UnknownHostException) {
            mThrowCallback.onFailure(UNKNOWN_CODE, AwBaseApplication.getInstance().getString(R.string.common_net_server_abnormal_request));
        } else if(e instanceof SocketTimeoutException) {
            mThrowCallback.onFailure(UNKNOWN_CODE, AwBaseApplication.getInstance().getString(R.string.common_net_server_abnormal_timeout));
        } else if(e instanceof ConnectException) {
            mThrowCallback.onFailure(UNKNOWN_CODE, AwBaseApplication.getInstance().getString(R.string.common_net_server_abnormal_connect));
        } else if(e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            mThrowCallback.onFailure(UNKNOWN_CODE, AwBaseApplication.getInstance().getString(R.string.common_net_server_abnormal_parse));
        } else if(e instanceof ApiException) {
            ApiException exception = (ApiException) e;
            if (exception.isTokenExpried()) {
                //处理token失效对应的逻辑
                EventBus.getDefault().postSticky(new EventReLoginType(null));
            } else {
                mThrowCallback.onFailure(exception.getErrorCode(), exception.getMsg());
            }

        } else {
            if (e.getMessage() != null && e.getMessage().contains("failed") || e.getMessage().contains("Failed")) {
                mThrowCallback.onFailure(UNKNOWN_CODE, AwBaseApplication.getInstance().getString(R.string.common_net_abnormal));
            } else {
                mThrowCallback.onFailure(UNKNOWN_CODE, e.getMessage());
            }
        }
    }
}
